package cc.monggo.web.controller.login;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cc.monggo.common.AbstractBaseController;
import cc.monggo.common.Constants;
import cc.monggo.domain.XThirdUser;
import cc.monggo.third.QQService;
import cc.monggo.third.RenrenService;
import cc.monggo.third.SinaService;
import cc.monggo.third.client.ConfigUtil;
import cc.monggo.third.impl.QQServiceImpl;
import cc.monggo.third.impl.RenrenServiceImpl;
import cc.monggo.third.impl.SinaServiceImpl;
import cc.monggo.third.model.QQAccessToken;
import cc.monggo.third.model.QQUser;
import cc.monggo.third.model.RenrenUser;
import cc.monggo.third.model.SinaAccessToken;
import cc.monggo.third.model.SinaUser;
import cc.monggo.utils.EncrypTool;
import cc.monggo.web.form.RegisterForm;

@Controller
@RequestMapping("/auth")
public class ThirdLoginController extends AbstractBaseController {		
	private static String qqApiUrl    			= ConfigUtil.getValue("qqApiUrl");
	private static String qqApiKey   			= ConfigUtil.getValue("qqApiKey");
	private static String qqApiSecret			= ConfigUtil.getValue("qqApiSecret");
	private static String qqApiRedirect_uri		= ConfigUtil.getValue("qqApiRedirect_uri");
	
	private static String sinaApiUrl    		= ConfigUtil.getValue("sinaApiUrl");
	private static String sinaApiKey   			= ConfigUtil.getValue("sinaApiKey");
	private static String sinaApiSecret			= ConfigUtil.getValue("sinaApiSecret");
	private static String sinaApiRedirect_uri	= ConfigUtil.getValue("sinaApiRedirect_uri");
	
	private static String renrenApiUrl     		= ConfigUtil.getValue("renrenApiUrl");
	private static String renrenApiKey     		= ConfigUtil.getValue("renrenApiKey");
	private static String renrenApiSecret  		= ConfigUtil.getValue("renrenApiSecret");
	private static String renrenAppID      		= ConfigUtil.getValue("renrenAppID");
	private static String renrenApiRedirect_uri = ConfigUtil.getValue("renrenApiRedirect_uri");
	
	/**
	 * QQ进入登陆页
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/qq/logon")
	public ModelAndView qqLogon(HttpServletRequest request) {
		StringBuffer url = new StringBuffer();
		url.append("https://").append(qqApiUrl).append("/oauth2.0/authorize")
		.append("?client_id=").append(qqApiKey)
		.append("&redirect_uri=").append(qqApiRedirect_uri)
		.append("&response_type=").append("code");
		ModelAndView mv = new ModelAndView("/logon/third_logon",Constants.FORM_COMMAND_KEY,url.toString());
		return mv;
	}
	
	/**
	 * 新浪微博 进入登陆页
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/sina/logon")
	public ModelAndView sinaLogon(HttpServletRequest request) {
		StringBuffer url = new StringBuffer();
		url.append("https://").append(sinaApiUrl).append("/oauth2/authorize")
		.append("?client_id=").append(sinaApiKey)
		.append("&redirect_uri=").append(sinaApiRedirect_uri)
		.append("&response_type=").append("code");
		ModelAndView mv = new ModelAndView("/logon/third_logon",Constants.FORM_COMMAND_KEY,url.toString());
		return mv;
	}
	
	/**
	 * 人人网登陆页
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/renren/logon")
	public ModelAndView renrenLogon(HttpServletRequest request) {
		StringBuffer url = new StringBuffer();
		url.append("https://").append(renrenApiUrl).append("/oauth/authorize")
		.append("?client_id=").append(renrenApiKey)
		.append("&redirect_uri=").append(renrenApiRedirect_uri)
		.append("&response_type=").append("code");
		ModelAndView mv = new ModelAndView("/logon/third_logon",Constants.FORM_COMMAND_KEY,url.toString());
		return mv;
	}
	 
	/**
	 * 登陆QQ后返回
	 * 
	 * @param request
	 * @param command
	 * @return
	 */
	@RequestMapping(value = "/qq/callback")
	public ModelAndView callbackQQ(HttpServletRequest request,RegisterForm form) {
		String code = request.getParameter("code");
		if (!StringUtils.isBlank(code)) {
			try {
				HashMap<String, String> params = new HashMap<String, String>();
				
				params.put("host", qqApiUrl);
				params.put("port", "443");
				params.put("protocol", "https");
				params.put("path", "/oauth2.0/token");
				
				params.put("client_id", qqApiKey);
				params.put("client_secret", qqApiSecret);
				params.put("grant_type", "authorization_code");
				
				params.put("redirect_uri",qqApiRedirect_uri);
				params.put("state", "abc123");
				params.put("code", code);

				QQService qqService = new QQServiceImpl();
				QQAccessToken accessToken = qqService.getAccessToken(params);
				if (accessToken != null) {
					if (!StringUtils.isBlank(accessToken.getAccessToken())) {
						String access_token = accessToken.getAccessToken();
						params.remove("code");
						params.put("port", "443");
						params.put("protocol", "https");				
						params.put("access_token", access_token);
						params.put("path", "/oauth2.0/me");
						String openId = qqService.getOpenId(params);
						if(!StringUtils.isBlank(openId)){
							params.put("path", "/user/get_user_info");
							params.put("oauth_consumer_key", "100268784");
							params.put("openid", openId);					
							QQUser qqUser = qqService.getUser(params);
							if(!StringUtils.isBlank(qqUser.getNickname())){
								form.setThirdId(openId);
								form.setNickname(qqUser.getNickname());						
								form.setAccessToken(accessToken.getAccessToken());
								form.setExpiresin(accessToken.getExpiresIn());																				
								form.setImageUrlSmall(qqUser.getFigureurl_50());
								
								form.setImageUrlLarge(qqUser.getFigureurl_100());							
								form.setType(Constants.USER_THIRD_TYPE_QQ); 
								 
								form.form2XThirdUser();		
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		ModelAndView mv = chooseMV(form.getxThirdUser());
		return mv;
	}
	
	/**
	 * 登陆新浪后返回
	 * 
	 * @param request
	 * @param command
	 * @return
	 */
	@RequestMapping(value = "/sina/callback")
	public ModelAndView callbackSina(HttpServletRequest request,RegisterForm form) {
		String code = request.getParameter("code");
		if (!StringUtils.isBlank(code)) {
			try {
				HashMap<String, String> params = new HashMap<String, String>();
				params.put("host", sinaApiUrl);
				params.put("port", "80");
				params.put("protocol", "http");
				params.put("path", "/2/oauth2/access_token");
				params.put("client_id", sinaApiKey);
				params.put("client_secret", sinaApiSecret);
				params.put("grant_type", "authorization_code");
				params.put("redirect_uri",sinaApiRedirect_uri);
				params.put("code", code);

				SinaService sinaService = new SinaServiceImpl();
				SinaAccessToken accessToken = sinaService.getAccessToken(params);
				if (accessToken != null) {
					if (!StringUtils.isBlank(accessToken.getAccessToken())) {
						String access_token = accessToken.getAccessToken();
						String uid = accessToken.getUid();
						params.remove("code");
						params.put("port", "443");
						params.put("protocol", "https");
						params.put("access_token", access_token);
						params.put("uid", uid);
						params.put("path", "/2/users/show.json");
						SinaUser sinaUser = sinaService.getUser(params);				
						if(!StringUtils.isBlank(sinaUser.getSrceen_name())){
							form.setThirdId(accessToken.getUid());
							form.setNickname(sinaUser.getSrceen_name());						
							form.setAccessToken(accessToken.getAccessToken());
							form.setExpiresin(accessToken.getExpiresIn());																				
							form.setImageUrlSmall(sinaUser.getProfileImageUrl());
							
							form.setImageUrlLarge(sinaUser.getProfileImageUrl_large());							
							form.setType(Constants.USER_THIRD_TYPE_SINA); 
							 
							form.form2XThirdUser();						  
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		ModelAndView mv = chooseMV(form.getxThirdUser());
		return mv;
	}
	
	/**
	 * 登陆人人后返回
	 * 
	 * @param request
	 * @param command
	 * @return
	 */
	@RequestMapping(value = "/renren/callback")
	public ModelAndView callbackRenren(HttpServletRequest request,RegisterForm form) {
		String code = request.getParameter("code");
		if (!StringUtils.isBlank(code)) {
			try {
				HashMap<String, String> params = new HashMap<String, String>();
				params.put("host", renrenApiUrl);
				params.put("port", "443");
				params.put("protocol", "https");
				params.put("path", "/oauth/token");
				
				params.put("client_id",renrenApiKey);
				params.put("client_secret", renrenApiSecret);
				params.put("grant_type", "authorization_code");
				
				params.put("redirect_uri",renrenApiRedirect_uri);
				params.put("code", code);
				
				RenrenService renrenService = new RenrenServiceImpl();
				RenrenUser renrenUser = renrenService.getAccessToken(params);
				if(!StringUtils.isBlank(renrenUser.getName()) && !StringUtils.isBlank(renrenUser.getAccessToken())){
					form.setThirdId(renrenUser.getId());
					form.setNickname(renrenUser.getName());						
					form.setAccessToken(renrenUser.getAccessToken());
					form.setExpiresin(renrenUser.getExpiresIn());																				
					form.setImageUrlSmall(renrenUser.getImageUrl_tiny());
					
					form.setImageUrlLarge(renrenUser.getImageUrl_large());							
					form.setType(Constants.USER_THIRD_TYPE_RENREN); 
					 
					form.form2XThirdUser();					
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		ModelAndView mv = chooseMV(form.getxThirdUser());
		return mv;
	}
	
	/**
	 * 选择一个走向
	 * 
	 * @param xThirdUser
	 * @return
	 */
	private ModelAndView chooseMV(XThirdUser xThirdUser){
		if(true){
			StringBuffer sb = new StringBuffer();
			sb.append("redirect:/register/third")
			.append("?thirdId=").append(EncrypTool.encode(xThirdUser.getThirdId()))
			.append("&nickname=").append(xThirdUser.getNickName())
			.append("&accessToken=").append(xThirdUser.getAccessToken())
			.append("&expiresin=").append(xThirdUser.getExpiresin())
			.append("&imageUrlSmall=").append(xThirdUser.getImageUrlSmall())
			.append("&imageUrlLarge=").append(xThirdUser.getImageUrlLarge())
			.append("&type=").append(xThirdUser.getType());
			ModelAndView mv = new ModelAndView(sb.toString());
			return mv;
		}
		
		XThirdUser newXThirdUser = registerService.selectByThirdIdAndType(xThirdUser.getThirdId(),xThirdUser.getType());
		if(newXThirdUser != null){
			if(!StringUtils.isBlank(newXThirdUser.getThirdId())){
				return null;
			}else{
				return null;
			}
		}else{
			StringBuffer sb = new StringBuffer();
			sb.append("redirect:/register/third")
			.append("?thirdId=").append(EncrypTool.encode(xThirdUser.getThirdId()))
			.append("&nickname=").append(xThirdUser.getNickName())
			.append("&accessToken=").append(xThirdUser.getAccessToken())
			.append("&expiresin=").append(xThirdUser.getExpiresin())
			.append("&imageUrlSmall=").append(xThirdUser.getImageUrlSmall())
			.append("&imageUrlLarge=").append(xThirdUser.getImageUrlLarge())
			.append("&type=").append(xThirdUser.getType());
			ModelAndView mv = new ModelAndView(sb.toString());
			return mv;
		}	
	}
}
